package prototipo.server.logic.util;

import prototipo.server.logic.exception.ExceptionLogic;

/**
 * This class represents the cep. A street's identification used in Brazil.
 * 
 * @author cayo
 * 
 */
public class Cep implements CepIF {

	private String cep;

	public Cep(String newCep) throws ExceptionLogic {
		this.setCep(newCep);
	}

	public Cep() {

	}

	/**
	 * @return the cep
	 */
	public String getCep() {
		return cep;
	}

	/**
	 * @param cep
	 *            the cep to set
	 * @throws ExceptionLogic
	 */
	public void setCep(String cep) throws ExceptionLogic {
		if (cep != null)
			if (validateCep(cep))
				this.cep = cep;
	}

	/**
	 * Check if the cep is in the correct pattern.
	 * 
	 * @param cep2
	 * @throws ExceptionLogic
	 */
	private boolean validateCep(String cep2) throws ExceptionLogic {
		if (cep2.length() != 8)
			throw new ExceptionLogic("Insira um cep valido.", new Throwable(
					"Cep length is direfent of 8."));
		try {
			Integer.parseInt(cep2);
			if (cep2.contains("-"))
				throw new ExceptionLogic("Insira um cep valido.",
						new Throwable("Any caracters' cep are not number."));
		} catch (NumberFormatException e) {
			throw new ExceptionLogic("Insira um cep valido.", new Throwable(
					"Any caracters' cep are not number."));
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((cep == null) ? 0 : cep.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Cep))
			return false;
		Cep other = (Cep) obj;
		if (cep == null) {
			if (other.cep != null)
				return false;
		} else if (!cep.equals(other.cep))
			return false;
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return String.format("%s-%s", this.cep.substring(0, 5), this.cep
				.substring(5, 8));
	}
}
